<template>
  <view>
    <view class="common content">
      <u-divider text="基本信息"></u-divider>
      <u-skeleton
          :loading="dataForm.control.loadingSkeletonVisible"
          rows="15"
          :title="false"
      >
        <u--form labelPosition="left" :model="dataForm.bookInfo" ref="dataForm">
          <u-form-item label="书名" prop="name" border-bottom>
            <u-input v-model="dataForm.bookInfo.name" border="none"></u-input>
          </u-form-item>
          <u-form-item label="作者" prop="author" border-bottom>
            <u-input v-model="dataForm.bookInfo.author" border="none"></u-input>
          </u-form-item>
          <u-form-item label-width="55" label="出版社" prop="pubHouse" border-bottom>
            <u-input v-model="dataForm.bookInfo.pubHouse" border="none"></u-input>
          </u-form-item>
          <u-form-item @click="inTimePickerVisibleSwitch" label-width="70" label="出版日期" prop="pubDate"
                       border-bottom>
            <u-input
                :value="getTime(dataForm.bookInfo.pubDate)"
                disabled
                disabledColor="#fff"
                border="none">
              <template slot="suffix">
                <u-icon name="arrow-right"></u-icon>
              </template>
            </u-input>
            <u-icon slot="right" color="#fff" name="arrow-right"></u-icon>
            <u-datetime-picker
                @close="inTimePickerVisibleSwitch"
                @confirm="setPubDate()"
                :min-date="157737600000"
                :show="dataForm.control.inTimePickerVisible"
                v-model="dataForm.bookInfo.pubDate"
                mode="date">
            </u-datetime-picker>
          </u-form-item>
          <u-form-item label="ISBN" prop="isbn" border-bottom>
            <u-input v-model="dataForm.bookInfo.isbn" border="none">
              <template slot="suffix">
                <u-button @click="scanISBN" :custom-style="{border: 'none'}" size="large" :hairline="false"
                          icon="scan"></u-button>
              </template>
            </u-input>
          </u-form-item>
          <u-form-item label="简介" prop="desc">
            <u-textarea count
                        auto-height
                        :height="100"
                        maxlength="300"
                        :auto-height="false"
                        v-model="dataForm.bookInfo.desc"
                        placeholder="请输入简介">
            </u-textarea>
          </u-form-item>
          <u-form-item label="封面" prop="cover" border-bottom>
            <u-input
                v-model="dataForm.bookInfo.cover"
                placeholder="https://开头的图片路径"
                border="none">
              <template slot="suffix">
                <u-button @click="coverVisibleSwitch"
                          :custom-style="{'border': 'none'}"
                          :hairline="false"
                          icon="photo">
                </u-button>
              </template>
            </u-input>
            <u-modal
                @close="coverVisibleSwitch"
                :show="dataForm.control.coverVisible"
                :show-confirm-button="false"
                close-on-click-overlay>
              <template slot="default">
                <u-image
                    @click="coverVisibleSwitch"
                    showLoading
                    height="400"
                    width="250"
                    mode="aspectFit"
                    :src="dataForm.bookInfo.cover">
                </u-image>
              </template>
            </u-modal>
          </u-form-item>
          <!--标签-->
          <u-form-item @click="labelsSheetVisibleSwitch" label="标签" prop="labels">
            <u-input
                :value="Number(dataForm.bookInfo.labels.length) === 0 ? '' : `已关联${dataForm.bookInfo.labels.length}个标签`"
                disabled
                disabledColor="#fff"
                border="none">
              <template slot="suffix">
                <u-icon name="arrow-right"></u-icon>
              </template>
            </u-input>
            <u-icon slot="right" color="#fff" name="arrow-right"></u-icon>
            <u-action-sheet
                @close="labelsSheetVisibleSwitch"
                :show="dataForm.control.labelsSheetVisible"
                :close-on-click-overlay="false"
                :round="20"
                title="关联标签"
                cancelText="确定">
              <template slot="default">
                <view style="display: flex;margin:15px;flex-wrap: wrap;justify-content: flex-start">
                  <view
                      style="display: flex;height: 45px;margin-right:15px;align-items: flex-end;justify-content: center"
                      v-for="(item,index) in dataForm.labels"
                      :key="index">
                    <u-tag @click="labelsCheckedOpen(index,item._id)"
                           @close="labelsCheckedClose(index,item._id)"
                           size="large"
                           shape="circle"
                           :name="item._id"
                           :border-color="item.color"
                           :color="dataForm.control.labelsChecked[index]?'#fff':item.color"
                           :bg-color="!dataForm.control.labelsChecked[index]?'#fff':item.color"
                           :plain="!dataForm.control.labelsChecked[index]"
                           :closable="dataForm.control.labelsChecked[index]"
                           :text="item.content">
                    </u-tag>
                  </view>
                </view>
              </template>
            </u-action-sheet>
          </u-form-item>
          <u-divider text="扩展信息"></u-divider>
          <u-form-item @click="storageTimePickerVisibleSwitch" label-width="70" label="入库日期" prop="pubDate"
                       border-bottom>
            <u-input
                :value="getTime(dataForm.bookInfo.storageDate)"
                disabled
                disabledColor="#fff"
                border="none">
              <template slot="suffix">
                <u-icon name="arrow-right"></u-icon>
              </template>
            </u-input>
            <u-icon slot="right" color="#fff" name="arrow-right"></u-icon>
            <u-datetime-picker
                @close="storageTimePickerVisibleSwitch"
                @confirm="setStorageDate()"
                :show="dataForm.control.storageTimePickerVisible"
                v-model="dataForm.bookInfo.storageDate"
                mode="date">
            </u-datetime-picker>
          </u-form-item>
          <u-form-item label="页数" prop="pages" border-bottom>
            <u-input v-model="dataForm.bookInfo.pages" border="none"></u-input>
          </u-form-item>
          <u-form-item label-width="80" label="价格（元）" prop="price" border-bottom>
            <u-input v-model="dataForm.bookInfo.price" border="none"></u-input>
          </u-form-item>
          <u-form-item @click="languagePickerVisibleSwitch" label="语言" prop="language" border-bottom>
            <u-input
                v-model="dataForm.bookInfo.language"
                disabled
                disabledColor="#fff"
                border="none">
              <template slot="suffix">
                <u-icon name="arrow-right"></u-icon>
              </template>
            </u-input>
            <u-icon slot="right" color="#fff" name="arrow-right"></u-icon>
            <u-picker
                @cancel="languagePickerVisibleSwitch"
                @confirm="setLanguage()"
                :show="dataForm.control.languagePickerVisible"
                :columns="languages">
            </u-picker>
          </u-form-item>
          <u-form-item label="备注" prop="ps">
            <u-textarea count
                        auto-height
                        :height="60"
                        maxlength="120"
                        :auto-height="false"
                        v-model="dataForm.bookInfo.ps">
            </u-textarea>
          </u-form-item>
          <u-row :custom-style="{'margin-top': '10rpx'}" justify="center">
            <u-col span="8">
              <u-button
                  shape="circle"
                  type="primary"
                  :loading="dataForm.control.saveButtonDisable"
                  :disabled="dataForm.control.saveButtonDisable"
                  @click="saveBookInfo"
              >确定
              </u-button>
            </u-col>
          </u-row>
        </u--form>
        <u-row :custom-style="{'margin-top': '10rpx'}" justify="center">
          <u-col span="8">
            <u-button
                shape="circle"
                type="info"
                :loading="dataForm.control.addMoreButtonDisable"
                :disabled="dataForm.control.addMoreButtonDisable"
                @click="addMore"
            >再来一本
            </u-button>
          </u-col>
        </u-row>
      </u-skeleton>
      <!--TODO 下边距-->
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import languages from '../common/language.json'
export default {
  async onLoad(query) {
    let bookId = query.bookId
    await this.getLabelInfo()
    if (query.scan) {
      this.scanISBN()
      return
    }
    if (!(bookId === undefined || bookId === null)) {
      this.dataForm.bookId = bookId
      await this.getBookInfo(bookId)
    }
  },
  created() {

  },
  data() {
    return {
      languages,
      title: '',
      dataForm: {
        control: {
          loadingSkeletonVisible: false,
          inTimePickerVisible: false,
          storageTimePickerVisible: false,
          languagePickerVisible: false,
          labelsSheetVisible: false,
          coverVisible: false,
          saveButtonDisable: false,
          addMoreButtonDisable:false,
          labelsChecked: []
        },
        bookInfo: {
          _id: '',
          bookId: '',
          name: '',
          isbn: '',
          cover: '',
          author: '',
          pubHouse: '',
          pubDate: '',
          storageDate: new Date().getTime(),
          pages: '',
          price: '',
          language: '',
          desc: '',
          ps: '',
          labels: []
        },
        labels: [],
        labelBond: [],
        //单独存储book._id
        bookId: '',
      },
    }
  },
  methods: {
    inTimePickerVisibleSwitch() {
      this.dataForm.control.inTimePickerVisible = !this.dataForm.control.inTimePickerVisible
    },
    storageTimePickerVisibleSwitch() {
      this.dataForm.control.storageTimePickerVisible = !this.dataForm.control.storageTimePickerVisible
    },
    languagePickerVisibleSwitch() {
      this.dataForm.control.languagePickerVisible = !this.dataForm.control.languagePickerVisible
    },
    labelsSheetVisibleSwitch() {
      this.dataForm.control.labelsSheetVisible = !this.dataForm.control.labelsSheetVisible
    },
    labelsCheckedOpen(index, labelId) {
      this.$set(this.dataForm.control.labelsChecked, index, true)
      //检查是否已经添加过了
      if (this.dataForm.bookInfo.labels.length > 0) {
        if (!this.dataForm.bookInfo.labels.some(value => value === this.dataForm.labels[index]._id))
          this.dataForm.bookInfo.labels.push(labelId)
      } else {
        this.dataForm.bookInfo.labels.push(labelId)
      }
    },
    labelsCheckedClose(index, labelId) {
      this.$set(this.dataForm.control.labelsChecked, index, false)
      this.dataForm.bookInfo.labels = this.dataForm.bookInfo.labels.filter(item => item !== labelId)
    },
    coverVisibleSwitch() {
      this.dataForm.control.coverVisible = !this.dataForm.control.coverVisible
    },
    scanISBN() {
      let _this = this
      this.dataForm.control.loadingSkeletonVisible = true
      let book = uniCloud.importObject('book')
      uni.scanCode({
        scanType: 'qrCode',
        async success(res) {
          let isbn = res.result
          _this.dataForm.bookInfo.isbn = isbn
          let bookInfo = await book.getBookInfo(isbn)
          _this.dataForm.bookInfo = {
            ..._this.dataForm.bookInfo,
            ...bookInfo
          }
          console.log(_this.dataForm.bookInfo)
        },
        fail(res) {
          _this.$refs.uToast.show({
            message: '扫码失败',
            type: 'error'
          })
        }
      })
      this.dataForm.control.loadingSkeletonVisible = false
    },
    setPubDate(data) {
      if (data !== null) {
        this.dataForm.bookInfo.pubDate = data.value
        this.inTimePickerVisibleSwitch()
      } else {
        // TODO 错误提示
      }
    },
    setStorageDate(data) {
      if (data !== null) {
        this.dataForm.bookInfo.storageDate = data.value
        this.storageTimePickerVisibleSwitch()
      } else {
        // TODO 错误提示
      }
    },
    setLanguage(data) {
      if (data !== null) {
        this.dataForm.bookInfo.language = data.value[0]
        this.languagePickerVisibleSwitch()
      } else {
        // TODO 错误提示
      }
    },
    //获取信息
    async getBookInfo(bookId) {
      this.dataForm.control.loadingSkeletonVisible = true
      try {
        let db = uniCloud.database()
        let dbCmd = db.command
        let $ = db.command.aggregate
        //获取图书信息
        this.dataForm.bookInfo = (await db.collection('book')
            .aggregate()
            .match({
              _id: bookId
            })
            .lookup({
              from: 'inner_label_book',
              let: {
                bId: '$_id'
              },
              pipeline: $.pipeline()
                  .match(dbCmd.expr($.eq(['$bookId', '$$bId'])))
                  .project({
                    _id: 1,
                    labelId: 1
                  })
                  .done(),
              as: 'labels'
            })
            .addFields({
              bookId: '$_id',
            })
            .end()).result.data[0]
        //保存标签已绑定数据
        this.dataForm.labelBond = []
        if (this.dataForm.bookInfo.labels.length > 0) {
          this.dataForm.labelBond = this.dataForm.bookInfo.labels.slice(0)
        }
        this.dataForm.bookInfo.labels.forEach((value, index, array) => {
          //显示已选
          this.dataForm.labels.forEach((value2, index2, array2) => {
            if (value2._id === value.labelId) {
              this.dataForm.control.labelsChecked[index2] = true
            }
          })
          array[index] = value.labelId
        })
      } catch (e) {
        console.log(e)
        this.$refs.uToast.show({
          message: String(e) || '获取图书信息失败',
          type: 'error'
        })
      } finally {
        this.dataForm.control.loadingSkeletonVisible = false
      }
    },
    //保存图书信息
    async saveBookInfo() {
      this.dataForm.control.saveButtonDisable = true
      try {
        let db = uniCloud.database()
        let dbCmd = db.command
        let $ = db.command.aggregate
        //移除多余的字段
        let bookInfo = {...this.dataForm.bookInfo}
        delete bookInfo.labels
        delete bookInfo.bookId
        delete bookInfo._id
        //判断是否是编辑信息
        if (this.dataForm.bookId) {
          //是编辑，更新信息
          await db.collection('book')
              .doc(this.dataForm.bookInfo.bookId)
              .update(bookInfo)
        } else {
          //不是编辑，先判断是否已经有此书
          let isConsist = (await db.collection('book')
              .where({
                isbn: this.dataForm.bookInfo.isbn
              })
              .get()).result.data.length
          if (isConsist > 0) {
            this.$refs.uToast.show({
              message: '该书已经存在',
              type: 'error'
            })
            return
          }
          //添加数据
          this.dataForm.bookId = (await db.collection('book')
              .add(bookInfo)).result.id
        }
        //保存标签绑定数据
        let bondDeleteList = []
        let bondAddList = []
        this.dataForm.labels.forEach((value1, index, array) => {
          //判断是否选择
          if (this.dataForm.bookInfo.labels.length > 0 && this.dataForm.bookInfo.labels.some(value2 => value2 === value1._id)) {
            let bondCon = true
            //判断是否已绑定
            if (this.dataForm.labelBond.length > 0) {
              if (this.dataForm.labelBond.some(value3 => value3.labelId === value1._id))
                bondCon = false
            }
            if (bondCon)
              bondAddList.push({
                bookId: this.dataForm.bookId,
                labelId: value1._id
              })
          } else {
            //没有选择，检查过去绑定信息
            if (this.dataForm.labelBond.length > 0) {
              this.dataForm.labelBond.forEach((value4, index, array) => {
                if (value4.labelId === value1._id)
                  bondDeleteList.push(value4._id)
              })
            }
          }
        })
        if (bondDeleteList.length > 0)
          await db.collection('inner_label_book')
              .where({
                _id: dbCmd.in(bondDeleteList)
              })
              .remove()
        if (bondAddList.length > 0)
          await db.collection('inner_label_book')
              .add(bondAddList)
        this.$refs.uToast.show({
          message: '保存成功',
          type: 'success'
        })
      } catch (e) {
        console.log(e)
        this.$refs.uToast.show({
          message: '保存失败'+String(e) || '保存失败',
          type: 'error'
        })
      } finally {
        this.dataForm.control.saveButtonDisable = false
        await this.getBookInfo(this.dataForm.bookId)
      }
    },
    async getLabelInfo(){
      this.dataForm.control.loadingSkeletonVisible = true
      try {
        let db = uniCloud.database()
        //获取所有标签数据
        this.dataForm.labels = (await db.collection('label')
            .get()).result.data
        //初始化labelChecked
        this.dataForm.control.labelsChecked = new Array(this.dataForm.labels.length).fill(false)
      }catch (e) {
        console.log(e)
        this.$refs.uToast.show({
          message: String(e) || '获取标签信息失败',
          type:'error'
        })
      }finally {
        this.dataForm.control.loadingSkeletonVisible = false
      }
    },
    // 再来一本
    addMore(){
      this.dataForm.bookInfo = {
        _id: '',
        bookId: '',
        name: '',
        isbn: '',
        cover: '',
        author: '',
        pubHouse: '',
        pubDate: '',
        storageDate: new Date().getTime(),
        pages: '',
        price: '',
        language: '',
        desc: '',
        ps: '',
        labels: []
      }
      this.dataForm.bookId = ''
      this.dataForm.labelBond = []
      this.scanISBN()
    }
  },

  computed: {
    getTime() {
      return function (timestamp) {
        if (timestamp === null || timestamp === '')
          return ''
        let date = new Date(timestamp)
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
        return String(Y + M + D)
      }
    },
    dateParse() {
      return function (str) {
        if (str === null || str === '')
          return ''
        let arr = str.split('')
        console.log(arr)
        if (arr.length === 4)
          return Date.parse(str)
        else if (arr.length === 6) {
          arr.splice(4, 0, '-')
          return Date.parse(arr.join(''))
        } else if (arr.length === 8) {
          arr.splice(4, 0, '-')
          arr.splice(7, 0, '-')
          return Date.parse(arr.join(''))
        } else return '157737600000'
      }
    }
  }
}

</script>
<style scoped>
.content {
  padding-bottom: 50px;
}
</style>
